package com.youpai.platform.vulture.service.support;

import com.youpai.platform.vulture.service.channel.DefaultVultureChannel;
import com.youpai.platform.vulture.service.channel.VultureChannel;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @date: 2022/7/10 16:19
 * @author: Anna
 * @version: 1.0
 * @description: Channel关系映射
 */
@Slf4j
public class VultureChannelSupport {

    private static final ConcurrentHashMap<Channel, VultureChannel> CHANNEL_RELATION_MAP = new ConcurrentHashMap<>(1 << 8);

    private static final ConcurrentHashMap<String, VultureChannel> ACC_ID_2_CHANNEL = new ConcurrentHashMap<>();

    public static VultureChannel getOrAddVultureChannel(Channel channel) {
        VultureChannel newVultureChannel = null;
        VultureChannel vultureChannel = CHANNEL_RELATION_MAP.get(channel);
        if (null == vultureChannel) {
            newVultureChannel = new DefaultVultureChannel(channel);
            vultureChannel = CHANNEL_RELATION_MAP.putIfAbsent(channel, newVultureChannel);
        }
        if (null == vultureChannel) {
            vultureChannel = newVultureChannel;
        }
        return vultureChannel;
    }

    public static VultureChannel getVultureChannel(Channel channel) {
        return CHANNEL_RELATION_MAP.get(channel);
    }

    public static void addHandShakeChannel(String accId, VultureChannel vultureChannel) {
        ACC_ID_2_CHANNEL.put(accId, vultureChannel);
    }

    public static VultureChannel getVultureChannelByAccId(String accId) {
        return ACC_ID_2_CHANNEL.get(accId);
    }

    public static void removeHandShakeChannel(String accId) {
        ACC_ID_2_CHANNEL.remove(accId);
    }

    public static void removeVultureChannel(Channel channel) {
        CHANNEL_RELATION_MAP.remove(channel);
    }

}
